package person.bing.fbcloud.handle;

import cn.hutool.core.io.FastByteArrayOutputStream;
import com.google.code.kaptcha.Producer;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import person.bing.fbcloud.common.core.constant.CommonConstant;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author: mengfanbing
 * @date: 2020/9/14 13:47
 */
@Slf4j
@Component
@AllArgsConstructor
public class ImageCodeHandle implements HandlerFunction<ServerResponse> {
//    @Autowired
    private Producer producer;
//    @Resource
    private RedisTemplate redisTemplate;
    @Override
    public Mono<ServerResponse> handle(ServerRequest request) {
        String randomStr = request.queryParam(CommonConstant.RANDOM_STR).get();
        String text = producer.createText();
        redisTemplate.opsForValue().set(CommonConstant.DEFAULT_CODE + randomStr,text,60, TimeUnit.SECONDS);
        BufferedImage image = producer.createImage(text);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image,"jpeg",os);
        } catch (IOException e) {
            String error = "io write error";
            log.error(error);
            return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.TEXT_PLAIN).body(BodyInserters.fromObject(error));
        }
        return ServerResponse
                .status(HttpStatus.OK)
                .contentType(MediaType.IMAGE_JPEG)
                .body(BodyInserters.fromResource(new ByteArrayResource(os.toByteArray())));
    }
}
